#include <boost/regex.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>

#include "rtl_parser.h"

using namespace boost::filesystem;

void RtlParser::ParseFile(Context& context, const std::string& path_str)
{
    ifstream file(path_str);
    std::stringstream content;
    content << file.rdbuf();
    std::string line;
    // TODO: to check (C&)
    boost::regex reg_func(";; Function ([^\\s]+ )*\\((([\\w\\d_]+))\\)\n"); //[ \\w:_\\d\\(\\),\\|\\[\\]\\-<>\\*]
    //boost::regex reg_call("\\(call_insn (\\d )+([^\\s]+) \\(set \\([\\w\\d:\\ ]+\\)\\s+\\(call \\(mem:QI \\(symbol_ref[^\\s]+\\s+\\(\"([^\\s])\"\\)");
    boost::regex reg_call("\\(call_insn (\\d+ )+([^\\s]+) (\\(set \\([\\w\\d:\\ ]+\\))?\\s*\\(call \\(mem:QI \\(symbol_ref[^\\s]+\\s+\\(\"([^\\s]+)\"\\)");
    boost::smatch func_match_first;
    boost::smatch func_match_second;
    boost::smatch call_match;

    std::string::const_iterator xItStart = content.str().begin();
    std::string::const_iterator xItEnd = content.str().end();
   // bool funct_found = true;
    while (true) {
     //   funct_found = false;
        if (! boost::regex_search(xItStart, xItEnd, func_match_first, reg_func)) {
            break;
        }
        std::cout << "Function " << func_match_first[func_match_first.size() -1] << "\n";
        std::string::const_iterator call_start = func_match_first[0].second;
        std::string::const_iterator call_end = xItEnd;

        if (boost::regex_search(func_match_first[0].second, xItEnd, func_match_second, reg_func)) {
            xItStart = func_match_second[0].first;
            call_end = func_match_second[0].first;
        }
        else {
            xItStart = xItEnd;
        }
        //std::string str (call_start, call_end);
       // std::cout << str;
        while (boost::regex_search(call_start, call_end, call_match, reg_call)) {
            call_start = call_match[0].second;
            std::cout << "Call block : " << call_match[1] << " " << call_match[call_match.size() - 1] << "\n";
        }
    }



//    while( boost::regex_search(xItStart, xItEnd, func_match_first, reg_func) )
//    {
//        while (boost::regex_search(func_match_first[0].second, xItEnd,
//        xItStart = results[0].second;
//        std::cout << "Match: " << results[0] << "\n" ;
//        for (int i = 1; i < results.size(); ++i) {
//            std::cout << " Id: " << i << " "<< results[i] << "\n";
//        }
//    }


}
